package ecnu.ecgbackend.controller;
import ecnu.ecgbackend.service.*;
import ecnu.ecgbackend.utils.Result;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/file")
public class DiagnosisFileController {
    @Resource
    private DiagnosisFileService diagnosisFileService;

    @PreAuthorize("hasAnyAuthority('patient','developer')")
    @PostMapping("/chunk/upload")
    public Result chunkUpload(Integer index,
                              Integer totalChunks,
                              String fileName,
                              Integer interval,
                              Integer length,
                              @RequestParam("content") MultipartFile multipartFile)throws IOException {
        return diagnosisFileService.uploadChunk(index,fileName,interval,length,multipartFile);
    }
    @PreAuthorize("hasAnyAuthority('patient','developer')")
    @PostMapping("/chunk/merge")
    public Result chunkMerge( String fileName,String category){
        try {
            return diagnosisFileService.mergeChunk(fileName,category);
        }catch (IOException e){
            return Result.error().code(500).message(e.getMessage());
        }

    }
    @PreAuthorize("hasAnyAuthority('patient','developer','doctor')")
    @GetMapping("/data")
    public Result getFileData(@RequestParam(name = "rawDataId")String rawDataId,@RequestParam(name = "startTime")Integer startTime) {
        try {
            return diagnosisFileService.getDataSegment(rawDataId,startTime);
        }catch (IOException e) {
            return Result.error().code(500).message(e.getMessage());
        }
    }
    @PreAuthorize("hasAnyAuthority('patient','developer')")
    @GetMapping("/sample")
    public Result getDataSample(@RequestParam(name = "fileName")String fileName,@RequestParam(name = "index")Integer index) {
        try{
            return diagnosisFileService.getDataSample(fileName,index);
        }catch (IOException e) {
            return Result.error().code(500).message(e.getMessage());
        }
    }
    @PreAuthorize("hasAnyAuthority('patient','developer')")
    @GetMapping("/list")
    public Result getFiles() {
        List<String> files= diagnosisFileService.getFileList();
        return Result.ok(files);
    }
    @GetMapping("/info")
    public Result queryFileInfo(@RequestParam(name="rawDataId")String rawDataId){
        return Result.ok(diagnosisFileService.getFileInfo(rawDataId));
    }
}
